<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./style/common.css">
  <title>云手机列表</title>
  <style>
    .phone-list {
      position: relative;
      border: 1px solid #DFE1E6;
      background-color: #ffffff;
      width: 375px;
      height: 800px;
      border-radius: 3px;
      box-sizing: border-box;
    }
    .phone-item {
      width: 100%;
      height: 96%;
      text-align: center;
      padding: 10px;
      border-radius: 10px;
      background-image: url(./images/mobileBg.png);
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-position: center;
    }
    .phone-item-normal {
      border: 1px solid #e9edfa;
      background-color: #ffffff;
      color: #000001;
    }
    .phone-item:hover {
      border: 1px solid #526ECC;
      background-color: #ffffff;
      color: #526ECC;
      cursor: pointer;
    }
    .phone-item-choose {
      border: 1px solid #526ECC;
      background-color: #ffffff;
      color: #526ECC;
      box-shadow: 0px 6px 15px 10px rgba(0,0,0,.1);
    }
    .phone-list-header {
      background-color: #ffffff;
      width: 100%;
      height: 65px;
      line-height: 50px;
      font-size: 18px;
      padding: 10px 20px;
      box-sizing: border-box;
      border-bottom: 1px solid #DFE1E6;
      color: rgba(0,0,0,.5);
      display: flex;
      justify-content: space-between;
    }
    .phone-list-body {
      width: 100%;
      height: calc(100% - 132px);
      display: flex;
      justify-content: center;
      align-items: flex-start;
      flex-wrap: wrap;
      padding: 20px;
      box-sizing: border-box;
    }
    .phone-list-footer {
      display: flex;
      justify-content: space-evenly;
      padding: 10px;
      width: 100%;
      overflow: hidden;
      border: 1px solid #eee;
      box-sizing: border-box;
      background-color: #ffffff;
      position: absolute;
      bottom: 0;
    }
    .phone-btn {
      font-size: 16px;
      border-radius: 3px;
      width: 150px;
      height: 45px;
      background-color: #526ECC;
      border: 2px solid #526ECC;
      color: #ffffff;
    }
    .register-circle {
      position: relative;
      width: 50px;
      height: 50px;
      border-radius: 50%;
    }
    .user-content {
      top: 6px;
      left: 8px;
      position: absolute;
      display: flex;
      width: 35px;
      height: 32px;
      align-items: center;
      flex-direction: column;
      justify-content: space-between;
    }
    .head {
      width: 16px;
      height: 16px;
      background-color: #526ECC;
      border-radius: 50%;
    }
    .body {
      width: 35px;
      height: 13px;
      background-color: #526ECC;
      border-radius: 16px 16px 0 0;
    }
    .exit-btn, .trust-btn {
      border-top: none;
      border-left: none;
      border-bottom: none;
      border-right: 1px solid #dfe1e6;
    }
    .exit-btn, .cancel-btn {
      width: 50%;
      height: 100%;
      text-align: center;
      background-color: #fff;
    }
    .trust-btn {
      width: 100%;
      height: 100%;
      text-align: center;
      background-color: #fff;
    }
    .cancel-btn {
      border: none;
    }
    .phone-img {
      width: 100%;
      height: 80%;
      background-image: url(./images/mobileBg.png);
      background-size: 85.5px;
      background-repeat: no-repeat;
      background-position: center;
    }
    .phone-name {
      width: 100%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      color: #fff;
      font-size: 24px;
      text-align: center;
    }
    .trust-msg {
      margin: 0px;
      text-align: left;
      font-size: 14px;
      text-indent: 2em;
    }
    @media screen and (max-width: 768px) {
      .phone-list {
        width: 100%;
      }
      .phone-list-body {
        margin-top: 65px;
      }
      .phone-item {
        width: 80%;
      }
      .phone-list-header {
        z-index: 9999;
        top: 0px;
        position: fixed;
      }
      .phone-list-footer {
        z-index: 9999;
        position: fixed;
        bottom: 0;
      }
      .register-circle {
        width: 40px;
        height: 40px;
      }
      .user-content {
        top: 4px;
        left: 2px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="phone-list" id="phoneList">
      <div class="phone-list-header">
        <div>华为云手机</div>
        <div class="register-circle" id="registerCircle" onclick="confirmModal()">
          <div class="user-content">
            <div class="head"></div>
            <div class="body"></div>
          </div>
        </div>
      </div>
      <div class="phone-list-body" id="phoneListBody"></div>
      <div class="phone-list-footer">
        <button type="button" class="phone-btn" onclick="getPhoneInfo()">连接云手机</button>
      </div>
    </div>
  </div>
  <div class="message-content" id="messageContent">
    <div class="message-modal">
      <div class="header-content">
        <p>温馨提示</p>
      </div>
      <div class="body-content">
        <p class="msg" id="alertMsg">退出登录吗？</p>
      </div>
      <div class="footer-content" id="footerContent">
        <button class="exit-btn" onclick="loginOut()">退出</button>
        <button class="cancel-btn" onclick="closeModal()">取消</button>
      </div>
    </div>
  </div>

  <div class="message-content" id="trustModal">
    <div class="message-modal">
      <div class="header-content">
        <p>信任目标机器</p>
      </div>
      <div class="body-content">
        <p class="trust-msg">首次接入需点击下方信任按钮进行信任。</p>
        <p class="trust-msg" id="mobileMsg">待信任页面停止刷新后，返回上一个页面。</p>
        <p class="trust-msg" id="pcMsg">在新页签中依次点击高级、继续前往，待页面停止刷新后，关闭信任页面。</p>
      </div>
      <div class="footer-content">
        <button id="trustBtn" class="trust-btn" onclick="trustHost()">信任</button>
      </div>
    </div>
  </div>
  <script src="./common.js"></script>
  <script>
    let commonParams = null;
    let phoneList = null;
    const channelType = {
      'socket': 'WebSocket',
      'rtc': 'WebRtc'
    };
    let headerConfig = null;
    window.onload =  function () {
      if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
        document.getElementById('mobileMsg').style.display = 'block';
        document.getElementById('pcMsg').style.display = 'none';
      } else {
        document.getElementById('pcMsg').style.display = 'block';
        document.getElementById('mobileMsg').style.display = 'none';
      }
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
      headerConfig = {
        'token': userInfo.token,
        'session_id': userInfo.session_id
      };
      getInterfaceDomain();
    }

    function getInterfaceDomain() {
      let jsonFilePath = window.location.href.replace('phone.html', 'common.json');
      xhrHttpRequest('GET', jsonFilePath, null).then((res) => {
        commonParams = JSON.parse(res);
        getUserPhoneList();
      }, error => {
        showResErrorMsg(error);
      });
    }

    function getUserPhoneList() {
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
      const listUrl = [commonParams.interfaceDomain, 'phone/list'].join('/');
      xhrHttpRequest('POST', listUrl, null, headerConfig).then((res) => {
        phoneList = JSON.parse(res);
        createPhoneListDom(phoneList);
      }, error => {
        const errorConfig = JSON.parse(error);
        showAlertModal(errorConfig.errorMsg, 'none');
        setTimeout(() => {
          closeModal();
          // 提示认证信息非法时，自动跳转至登录页
          if (errorConfig.errorCode === 'CPH.MANAGER.USER.00003') {
            goLoginPage();
          }
        },2000);
      });
    }

    function createPhoneListDom(phoneList) {
      const phoneListEle = document.getElementById('phoneList');
      const phoneListBody = document.getElementById('phoneListBody');
      // 当前考虑只分配了一个云手机
      for(let i=0; i<phoneList.length; i++) {
        const buttonEle = document.createElement('div');
        const phoneNameEle = document.createElement('div');
        phoneNameEle.classList.add('phone-name');
        phoneNameEle.innerHTML = phoneList[i].phone_name;
        buttonEle.id = phoneList[i].phone_id;
        buttonEle.title = phoneList[i].phone_name;
        buttonEle.classList.add('phone-item');
        buttonEle.classList.add('phone-item-normal');
        buttonEle.addEventListener('click',function(e) {
          toggleButton(buttonEle.id);
        });
        phoneListBody.appendChild(buttonEle);
        buttonEle.appendChild(phoneNameEle);
      }
    }

    function toggleButton(buttonId) {
      getPhoneInfo();
    }

    function confirmModal() {
      const alertMsg = '退出登录吗？';
      showAlertModal(alertMsg, 'flex');
    }

    function closeModal() {
      const messageContent = document.getElementById('messageContent');
      messageContent.style.display = 'none';
    }

    function loginOut() {
      const logoutUrl = [commonParams.interfaceDomain, 'user/logout'].join('/');
      xhrHttpRequest('POST', logoutUrl, null, headerConfig).then((res) => {
        sessionStorage.removeItem('userInfo');
        sessionStorage.removeItem('phoneList');
        closeModal();
        goLoginPage();
      }, error => {
        const errorConfig = JSON.parse(error);
        showAlertModal(errorConfig.errorMsg, 'none');
        setTimeout(() => {
          closeModal();
          // 提示认证信息非法时，自动跳转至登录页
          if (errorConfig.errorCode === 'CPH.MANAGER.USER.00003') {
            goLoginPage();
          }
        },2000);
      });
    }

    function goLoginPage() {
      let localHref = window.location.href;
      if (window.location.href.indexOf('phone.html') > -1) {
        localHref = window.location.href.replace('phone.html',  'login.html');
        window.location.href = localHref;
      }
    }

    function getPhoneInfo() {
      if (!phoneList.length) {
        const errorMsg = '您没有云手机';
        showAlertModal(errorMsg, 'none');
        setTimeout(() => {
          closeModal();
        },2000);
        return;
      }
      let isChecked = false;
      let phoneId = phoneList[0].phone_id;

      const allocateUrl = [commonParams.interfaceDomain, 'connection/allocate'].join('/');
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
      const params = JSON.stringify({
        'phone_id': phoneId,
        'client_type': 'HTML5'
      });

      xhrHttpRequest('POST', allocateUrl, params, headerConfig).then((res) => {
        sessionStorage.setItem('phoneInfo', res);
        sessionStorage.setItem('channelType', channelType.socket);
        const targetStr = res && [JSON.parse(res).ip, JSON.parse(res).port].join(':');
        showTrustModal(targetStr);
      }, error => {
        const errorConfig = JSON.parse(error);
        showAlertModal(errorConfig.errorMsg, 'none');
        setTimeout(() => {
          closeModal();
          // 提示认证信息非法时，自动跳转至登录页
          if (errorConfig.errorCode === 'CPH.MANAGER.USER.00003') {
            goLoginPage();
          }
        },2000);
      });
    }

    function trustHost() {
      const phoneInfo = JSON.parse(sessionStorage.getItem('phoneInfo'));
      const ipVal = phoneInfo.ip;
      const portVal = phoneInfo.port;
      window.open('https://' + [ipVal, portVal].join(':'), '_black');

      const targetStr = [ipVal, portVal].join(':');
      storageTrustTarget(targetStr);
      setTimeout(() => {
        closeTrustModal(true);
      }, 2000);
    }

    function showTrustModal(targetStr) {
      const trustTargetStr = sessionStorage.getItem('trustTargetList');
      let openModal = false;
      if (trustTargetStr) {
        const trustTargetList = JSON.parse(trustTargetStr);
        if (trustTargetList.includes(targetStr)) {
          openModal = false;
        } else {
          openModal = true;
        }
      } else {
        openModal = true;
      }

      if (openModal) {
        const trustModal = document.getElementById('trustModal');
        trustModal.style.display = 'flex';
        return;
      }

      goCloudPhonePage();
    }

    function storageTrustTarget(targetStr) {
      const trustTargetStr = sessionStorage.getItem('trustTargetList');
      if (trustTargetStr) {
        const trustTargetList = JSON.parse(trustTargetStr);
        trustTargetList.push(targetStr);
        sessionStorage.removeItem('trustTargetList');
        sessionStorage.setItem('trustTargetList', JSON.stringify(trustTargetList));
      } else {
        const trustTargetList = [targetStr];
        sessionStorage.setItem('trustTargetList', JSON.stringify(trustTargetList));
      }
    }

    function goCloudPhonePage() {
      let localHref = window.location.href;
      if (window.location.href.indexOf('phone.html') > -1) {
        localHref = window.location.href.replace('phone.html',  'demo.html');
      }

      window.location.href = localHref;
    }

    function closeTrustModal(isGudge) {
      const trustModal = document.getElementById('trustModal');
      trustModal.style.display = 'none';
      if (!isGudge) {
        return;
      }
      
      goCloudPhonePage();
    }

    function showAlertModal(errorMsg, btnStyle) {
      if (!errorMsg) {
        return;
      }
      const messageContent = document.getElementById('messageContent');
      const alertMsg = document.getElementById('alertMsg');
      const footerContent = document.getElementById('footerContent');
      alertMsg.innerHTML = errorMsg;
      footerContent.style.display = btnStyle;
      messageContent.style.display = 'flex';
    }
  </script>
</body>
</html>